<template>
    <div class="container">
        <Breadcrumb :items="['menu.biz', 'menu.biz.multi']" />
        <a-card title="总店管理">
            <a-space fill direction="vertical">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-button type="primary" @click="openModal" shape="round">
                            <template #icon><icon-plus /></template>
                            新建总店
                        </a-button>
                    </a-col>
                </a-row>
                <a-table :data="renderData" :loading="loading" :bordered="{ cell: true }" :pagination="pagination"
                    @page-change="onPageChange" @page-size-change="onPageSizeChange">
                    <template #columns>
                        <a-table-column title="ID" data-index="id" :width="80" />
                        <a-table-column title="Logo" data-index="logo" :width="60">
                            <template #cell="{ record }">
                                <a-image v-if="record.logo"
                                    :src="record.logo.startsWith('http') ? record.logo : record.logo_url || record.logo"
                                    width="40" />
                            </template>
                        </a-table-column>
                        <a-table-column title="名称" data-index="name" />
                        <a-table-column title="商家数量" data-index="biz_total" :width="120" />
                        <a-table-column title="电话" data-index="phone" :width="120" />
                        <a-table-column title="账号" data-index="account" :width="150" />
                        <a-table-column title="创建时间" data-index="created_at" :width="180" />
                        <a-table-column title="操作" align="center" :width="120">
                            <template #cell="{ record }">
                                <a-space size="mini">
                                    <a-link @click="openModal(record)">编辑</a-link>
                                    <a-popconfirm position="left" content="确定要删除这个总店吗？" @ok="handleDelete(record.id)">
                                        <a-link status="danger">删除</a-link>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </a-space>
        </a-card>

        <a-modal v-model:visible="modalVisible" width="750px" :title="formData.id ? '编辑总店' : '新建总店'" @before-ok="handleSubmit"
            @cancel="closeModal">
            <a-form :model="formData" ref="formRef" layout="vertical">
                <a-form-item field="name" label="总店名称" :rules="[{ required: true, message: '请输入总店名称' }]">
                    <a-input v-model="formData.name" placeholder="请输入总店名称" />
                </a-form-item>
                <a-form-item label="Logo" :rules="[{ required: true }]">
                    <a-upload list-type="picture" v-model="formData.logo" :custom-request="handleUpload" :limit="1"
                        :file-list="logoFileList" image-preview @before-remove="beforeRemove" />
                    <template #extra>
                        <div>请上传Logo图片，建议比例1:1</div>
                    </template>
                </a-form-item>
                <a-row :gutter="16">
                    <a-col :span="8">
                        <a-form-item field="phone" label="电话">
                            <a-input v-model="formData.phone" placeholder="请输入电话" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item field="account" label="账号" :rules="[{ required: true, message: '请输入账号' }]">
                            <a-input v-model="formData.account" placeholder="请输入账号" :disabled="!!formData.id" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item field="password" label="密码" v-if="!formData.id">
                            <a-input v-model="formData.password" placeholder="请输入密码" type="password" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { queryMultiList, submitMultiForm, delMulti, MultiRecord, MultiModel } from '@/api/multi';
import { uploadFile } from '@/api/upload';

const { loading, setLoading } = useLoading(true);
const modalVisible = ref(false);
const formRef = ref();
const logoFileList = ref<{ url: string }[]>([]);

const basePagination = {
    current: 1,
    pageSize: 10,
    total: 0,
};

const pagination = reactive({
    ...basePagination,
});

const generateFormData = () => ({
    id: 0,
    name: '',
    logo: '',
    phone: '',
    account: '',
    password: '',
});

const formData = ref<MultiModel>(generateFormData());
const renderData = ref<MultiRecord[]>([]);

const fetchData = async () => {
    setLoading(true);
    try {
        const { data } = await queryMultiList({
            current: pagination.current,
            pageSize: pagination.pageSize,
        });
        renderData.value = data.list.map(item => ({
            ...item,
            logo_url: item.logo && !item.logo.startsWith('http') ? item.logo : item.logo // 兼容本地和远程
        }));
        pagination.total = data.total;
    } catch (err) {
        Message.error('获取总店列表失败');
    } finally {
        setLoading(false);
    }
};

const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
};

const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
};

const openModal = (record?: MultiRecord) => {
    if (record) {
        formData.value = {
            id: record.id,
            name: record.name,
            logo: record.logo,
            phone: record.phone,
            account: record.account,
            password: '',
        };
        logoFileList.value = record.logo ? [{ url: record.logo.startsWith('http') ? record.logo : record.logo_url || record.logo }] : [];
    } else {
        formData.value = generateFormData();
        logoFileList.value = [];
    }
    modalVisible.value = true;
};

const closeModal = () => {
    modalVisible.value = false;
    formData.value = generateFormData();
    logoFileList.value = [];
};

const handleUpload = async (option: any) => {
    try {
        const { fileItem, onSuccess } = option;
        const uploadFormData = new FormData();
        uploadFormData.append('file', fileItem.file);
        const { data } = await uploadFile(uploadFormData);
        formData.value.logo = data.path;
        logoFileList.value = [{ url: data.url }];
        Message.success('上传成功');
        return { abort: () => { } };
    } catch (err) {
        Message.error('上传失败');
        return { abort: () => { } };
    }
};

const beforeRemove = (file: any) => {
    formData.value.logo = '';
    logoFileList.value = [];
    return true;
};

const handleSubmit = async (done: any) => {
    setLoading(true);
    try {
        await submitMultiForm(formData.value).then((res) => {
            Message.success(res.msg || '操作成功');
            closeModal();
            fetchData();
            done(true);
        });
    } catch (err) {
        done(false);
    } finally {
        setLoading(false);
    }
};

const handleDelete = async (id: number) => {
    try {
        await delMulti(id);
        Message.success('删除成功');
        fetchData();
    } catch (err) {
        Message.error('删除失败');
    }
};

onMounted(() => {
    fetchData();
});
</script>

<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;
}
</style>
